package com.ezops.security;

import org.apache.shiro.SecurityUtils;

import com.ezops.models.User;

/**
 * The security manager is a class that allows applications to implement a
 * security checks. It allows an application to determine, before performing a
 * sensitive operation, what the operation is and whether the current logged in
 * user has the permission to perform that.
 * <p>
 * The <code>SecurityManager</code> class contains method to expose the logged
 * in user and the permission checks.
 * <p>
 * 
 * The idea is to hide the underlying security framework, all security related
 * checks should be done by this class and directly accessing the API of the
 * underlying framework is discouraged.
 * 
 * @author vgaurav
 * 
 */
public abstract class EZOPSSecurityManager {

	/**
	 * Return the logged in user in the current thread context. If no one logged
	 * in then returns null.
	 * 
	 * @return
	 */
	public static User getCurrentLoggedInUser() {
		if (SecurityUtils.getSubject().getPrincipal() == null) {
			return null;
		}
		return (User) SecurityUtils.getSubject().getPrincipal();
	}

	/**
	 * Return true if the current logged in user has role with name @param
	 * roleName
	 * 
	 * @param roleName
	 * @return
	 */
	public static boolean loggedInUserHasRole(String roleName) {
		if (SecurityUtils.getSubject().getPrincipal() == null) {
			return false;
		}
		return SecurityUtils.getSubject().hasRole(roleName);
	}

	/**
	 * Return true if the current logged in user has permission with name @param
	 * permission
	 * 
	 * @param permission
	 * @return
	 */
	public static boolean loggedInUserHasPermission(String permission) {
		if (SecurityUtils.getSubject().getPrincipal() == null) {
			return false;
		}
		return SecurityUtils.getSubject().isPermitted(permission);
	}

}
